<template>
  <el-upload
    v-model:file-list="fileList"
    action="#" :http-request="beforeAvatarUpload"
    list-type="picture-card"
    multiple
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
  <el-divider border-style="dashed" />
  <div class="text-center mt30"><el-button type="primary" @click="saveUpload">确认</el-button></div>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { onMounted, ref, watch  } from 'vue';
import COS from 'cos-js-sdk-v5';
import { ElMessage } from 'element-plus';

import type { UploadUserFile } from 'element-plus'
import http from '../util/request';

const fileList = ref<UploadUserFile[]>([])
const files = ref<string[]>([])


const dialogImageUrl = ref('')
const dialogVisible = ref(false)
interface uploadData {
    id:number
    image: string
    prefix: string
}
const data = ref<uploadData>({id:0,image:'',prefix:''})
let cosConfig = ref<any>({})

const props = defineProps<{
    data:any
    fileList:any
}>()

watch(props,()=>{
  data.value = props.data
  fileList.value = props.fileList
  files.value = [];
  fileList.value.forEach((e:any) => {
    files.value.push(e.url)
    e.url = import.meta.env.VITE_FILE_HTTP + e.url
  });
  
},{ immediate: true })

const getUploadToken = () => {
  http.get('uploadToken').then(function(response:any) {
      cosConfig.value = response.data.data
  })
}

const beforeAvatarUpload = (rawFile:any) => {
  let file:any = rawFile.file
  let str:string = file.name;
  let specificChar:string = ".";
  let position:number = str.indexOf(specificChar);
  let file_suffix:string = str.substring(position + 1);
  if (file.size / 1024 / 1024 > 10) {
      ElMessage.error('图片不得大于10MB!')
      return false
  }

  if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
    ElMessage.error('图片格式错误!')
    return false
  }

  let cos:any ={}
  cos = new COS({
      getAuthorization: function (options:any, callback:any) {
          console.log(options)
          callback({
              TmpSecretId: cosConfig.value.credentials.tmpSecretId,
              TmpSecretKey: cosConfig.value.credentials.tmpSecretKey,
              SecurityToken: cosConfig.value.credentials.sessionToken,
              // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
              StartTime: cosConfig.value.startTime, // 时间戳，单位秒，如：1580000000
              ExpiredTime: cosConfig.value.expiredTime, // 时间戳，单位秒，如：1580000000
              ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
          });
      }
  });
  let key:string = data.value.prefix+ generateRandomString(18) + '.' + file_suffix
  cos.uploadFile({
      Bucket: 'huajing-1344106420', /* 填入您自己的存储桶，必须字段 */
      Region: 'ap-shanghai',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
      Key: key,  /* 存储在桶里的对象键（请注意唯一性不然在删除的时候会找到相同的key），必须字段 */
      SliceSize: 1024 * 1024 * 10,
      Body: file, // 上传文件对象
      onProgress: function(progressData:any) {
          console.log(JSON.stringify(progressData));
      }
  }, function(err:any, res:any) {
      console.log(err);
      if(res.statusCode == 200){
        files.value.push(key)
      }
      return true
  })
}

const saveUpload = () => {
  emit('saveUpload',files.value)
}

const emit = defineEmits(['saveUpload'])

onMounted(()=>{
  getUploadToken()
})

function generateRandomString(length:number) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }

  return Date.now() +'-'+ result;
}
</script>